//
//  ZYPurchaseTransactionModel.m
//  ZYPurchase
//
//  Created by wu on 2020/8/6.
//  Copyright © 2020 wu. All rights reserved.
//

#import "ZYPurchaseTransactionModel.h"
#import "ZYPurchaseDataBase.h"

#import <StoreKit/StoreKit.h>
#import <FMDB/FMDB.h>
#import <MJExtension/MJExtension.h>

@interface ZYPurchaseTransactionModel ()

// 数据库中主键id
@property (nonatomic, assign, readwrite) NSInteger sql_id;

/// 交易订单信息
@property (nonatomic, strong, readwrite) ZYPurchaseOrderModel *order;
@property (nonatomic, copy, readwrite) NSString *orderId;

@property (nonatomic, copy, readwrite) NSString *uuid;

@end

@implementation ZYPurchaseTransactionModel

+ (instancetype)formatIAPTransaction:(nonnull ZYPurchaseOrderModel *)order{
    if (!order) {
        return nil;
    }
    ZYPurchaseTransactionModel *retModel = [[ZYPurchaseTransactionModel alloc] init];
    retModel.uuid = [ZYPurchaseTransactionModel uuid];
    retModel.order = order;
    retModel.orderId = order.orderId;
    retModel.transactionStatus = ZYPurchaseTransactionStatus_Idle;
    retModel.paymentMethod = ZYPurchasePaymentMethod_IAP;
    return retModel;
}

- (void)setTransactionStatus:(ZYPurchaseTransactionStatus)transactionStatus{
    _transactionStatus = transactionStatus;
    
    switch (transactionStatus) {
        case ZYPurchaseTransactionStatus_Idle:
            self.order.paymentStatus = ZYPurchaseOrderPaymentStatus_Unpaid;
            break;
        case ZYPurchaseTransactionStatus_Purchasing:
            self.order.paymentStatus = ZYPurchaseOrderPaymentStatus_Paying;
            break;
        case ZYPurchaseTransactionStatus_Cancel:
        case ZYPurchaseTransactionStatus_Fail:
            self.order.paymentStatus = ZYPurchaseOrderPaymentStatus_Fail;
            break;
        case ZYPurchaseTransactionStatus_Success:
            self.order.paymentStatus = ZYPurchaseOrderPaymentStatus_Success;
            break;
        default:
            break;
    }
}

// 实例化
+ (instancetype)modelFromResultSet:(FMResultSet *)resultSet{
    if (!resultSet) {
        return nil;
    }
    NSString *orderStr = [resultSet stringForColumn:@"order_info"];
    NSString *transaction_idStr = [resultSet stringForColumn:@"transaction_id"];
    
    ZYPurchaseTransactionModel *retModel = [[ZYPurchaseTransactionModel alloc] init];
    retModel.uuid = [resultSet stringForColumn:@"uuid"];
    retModel.transactionStatus = [resultSet intForColumn:@"t_status"];
    
    retModel.paymentMethod = [resultSet intForColumn:@"payment_method"];
    retModel.error = [resultSet stringForColumn:@"error"];
    retModel.createTime = [resultSet doubleForColumn:@"create_time"];
    retModel.updateTime = [resultSet doubleForColumn:@"update_time"];
    retModel.sql_id = [resultSet intForColumn:@"id"];
    retModel.orderId = [resultSet stringForColumn:@"order_id"];
    if (transaction_idStr && (transaction_idStr.length > 0)) {
        retModel.transactionId = transaction_idStr;
    }
    if (orderStr && (orderStr.length > 0)) {
        retModel.order = [ZYPurchaseOrderModel mj_objectWithKeyValues:orderStr];
    }
    retModel.receipt_data_filename = [resultSet stringForColumn:@"receipt_data"];
    return retModel;
}

/// 开始处理订单
- (BOOL)startPayment{
    if (self.transactionStatus == ZYPurchaseTransactionStatus_Idle) {
        NSString *applicationUsername = [self formatApplicationUsername];
        if (!applicationUsername) {
            NSLog(@"订单缺少必要信息，无法支付");
            return NO;
        }
        [ZYPurchaseDataBase resetLastIAPApplicationUsernameInKeychain:applicationUsername];
        self.transactionStatus = ZYPurchaseTransactionStatus_TryPurchage;
        SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:self.order.IAPProduct];
        payment.applicationUsername = applicationUsername;
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
    return YES;
}

- (BOOL)isValuable{
    if (!self.uuid || (self.uuid.length == 0)) {
        return NO;
    }
    if (!self.orderId || (self.orderId.length == 0)) {
        return NO;
    }
    return YES;
}

+ (NSString*)uuid{
    CFUUIDRef puuid = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}

@end

@implementation ZYPurchaseTransactionModel (ApplicationUsername)

// ApplicationUsername 中获取用户id
+ (NSString *)fetchUserIdFromApplicationUsername:(nonnull NSString *)applicationUsername{
    NSArray *applicationUsernames = [self applicationUsernames:applicationUsername];
    if (!applicationUsernames) {
        return nil;
    }
    return applicationUsernames.firstObject;
}
// ApplicationUsername 中获取订单id
+ (NSString *)fetchOrderIdFromApplicationUsername:(nonnull NSString *)applicationUsername{
    NSArray *applicationUsernames = [self applicationUsernames:applicationUsername];
    if (!applicationUsernames) {
        return nil;
    }
    return applicationUsernames.lastObject;
}
+ (NSArray *)applicationUsernames:(NSString *)applicationUsername{
    if (!applicationUsername || (applicationUsername.length == 0)) {
        return nil;
    }
    NSArray *applicationUsernameArr = [applicationUsername componentsSeparatedByString:@","];
    if (applicationUsernameArr.count != 2) {
        return nil;
    }
    return applicationUsernameArr;
}
// 组装支付的 ApplicationUsername
- (NSString *)formatApplicationUsername{
    if (!self.orderId || (self.orderId.length == 0)) {
        return nil;
    }
    if (!self.order.userId || (self.order.userId.length == 0)) {
        return nil;
    }
    if (!self.order.IAPProduct) {
        return nil;
    }
    NSArray *applicationUsernameArr = @[self.order.userId, self.orderId];
    return [applicationUsernameArr componentsJoinedByString:@","];
}

// 状态值转状态描述
+ (NSString *)transactionStatusDescription:(ZYPurchaseTransactionStatus)status{
    NSDictionary *dict = @{@(ZYPurchaseTransactionStatus_Idle):@"Idle 空闲",
                           @(ZYPurchaseTransactionStatus_TryPurchage):@"TryPurchage 已发起购买",
                           @(ZYPurchaseTransactionStatus_Purchasing):@"Purchasing 购买中",
                           @(ZYPurchaseTransactionStatus_Verifing):@"Verifing 后台校验中",
                           @(ZYPurchaseTransactionStatus_Cancel):@"Cancel 交易已取消",
                           @(ZYPurchaseTransactionStatus_Fail):@"Fail 交易失败",
                           @(ZYPurchaseTransactionStatus_ReceiptInvalid):@"ReceiptInvalid 交易结束，收据校验不通过",
                           @(ZYPurchaseTransactionStatus_ReceiptWaitVerify):@"WaitVerify 交易结束，收据尚未校验（非网络原因）",
                           @(ZYPurchaseTransactionStatus_ReceiptWaitVerify_NetworkLost):@"WaitVerify_NetworkLost 交易结束，收据尚未校验（网络原因）",
                           @(ZYPurchaseTransactionStatus_Success):@"Success 交易完成",
                           @(ZYPurchaseTransactionStatus_Restored):@"Restored 续费完成",
                           @(ZYPurchaseTransactionStatus_RePurchase): @"RePurchase 重复购买"
    };
    if ([dict.allKeys containsObject:@(status)]) {
        return [dict objectForKey:@(status)];
    }
    return @"未知";
}

@end

@implementation ZYPurchaseTransactionModel (Receipt)

// 获取收据存储的沙盒路径
- (nullable NSString *)receiptDataFilePath{
    return [ZYPurchaseTransactionModel receiptDataFilePathForFileName:self.receipt_data_filename];
}
+ (nullable NSString *)receiptDataFilePathForFileName:(nonnull NSString *)fileName{
    if (!fileName || (fileName.length == 0)) {
        return nil;
    }
    return [ZYPurchaseDataBase.purchaseReceiptDirectoryPath stringByAppendingPathComponent:fileName];
}
// 生成收据名称
+ (NSString *)generateReceiptDataFileName{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    NSString *cueDateString = [dateFormatter stringFromDate:[NSDate date]];
    NSString *fileNameWithoutExtension = [NSString stringWithFormat:@"receipt_%@_", cueDateString, arc4random()%1000];
    return [fileNameWithoutExtension stringByAppendingString:@".txt"];
}

// 本地存储的收据
- (nullable NSString *)receiptDataLocal{
    return [ZYPurchaseTransactionModel receiptStringWithName:self.receipt_data_filename];
}
// 根据收据文件名称获取收据字符串
+ (nullable NSString *)receiptStringWithName:(NSString *)fileName{
    if (!fileName || (fileName.length == 0)) {
        return nil;
    }
    NSString *filePath = [ZYPurchaseTransactionModel receiptDataFilePathForFileName:fileName];
    if (!filePath) {
        return nil;
    }
    BOOL isDirectory = NO;
    BOOL exist = [NSFileManager.defaultManager fileExistsAtPath:filePath isDirectory:&isDirectory];
    if (!exist || isDirectory) {
        return nil;
    }
    NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    return content;
}
// 存储收据到本地
+ (BOOL)saveReceiptData:(nonnull NSString *)receiptInfo
                     at:(nonnull NSString *)filePath{
    if (!receiptInfo || (receiptInfo.length == 0) ||
        !filePath || (filePath.length == 0)) {
        return NO;
    }
    NSError *error = nil;
    [receiptInfo writeToFile:filePath
                  atomically:YES
                    encoding:NSUTF8StringEncoding
                       error:&error];
    return error?NO:YES;
}

@end
